package com.netsdk.config;

import com.alibaba.fastjson.JSONObject;
import com.netsdk.common.AnalyzerDataCallBack;
import com.netsdk.module.FaceRecognitionModule;
import com.netsdk.module.LoginModule;
import com.netsdk.lib.NetSDKLib;
import com.netsdk.utils.CoreUtil;
import com.sun.jna.Pointer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;

/**
 * 配置初始化
 * @author FZH
 * @version 1.0
 * @date 2025-09-05 14 10:00
 */
@Configuration
@Slf4j
public class InitConfig {
    public static JSONObject configFile;

    @PostConstruct
    public void init() {
        // 初始化SDK
        LoginModule.init(null, null);
        log.info("------------- 初始化SDK完成 -------------");

        // 初始化配置
        configFile = JSONObject.parseObject(CoreUtil.resourcesFile("conf.json"));
        if (configFile == null) {
            log.info("conf.json配置读取失败！");
            return;
        }

        JSONObject device = configFile.getJSONArray("device").getJSONObject(0);

        // 设备登录
        NetSDKLib.LLong login = LoginModule.login(device.getString("ip"), device.getIntValue("port"),
                device.getString("userName"), device.getString("password"));
        log.info("设备信息: {}\n, 登录状态: {}", device, login);

        String groupId = "";

//        groupId = FaceRecognitionModule.addGroup("fzh_face");
//        log.info("添加人脸库: {}", groupId);

        // 删除人脸库
//        FaceRecognitionModule.deleteGroup(groupId);

        // 查询人脸库
        NetSDKLib.NET_FACERECONGNITION_GROUP_INFO[] groupInfos = FaceRecognitionModule.findGroupInfo(groupId);
        if (groupInfos != null) {
            groupId = new String(groupInfos[0].szGroupId);
            log.info("查询人脸库: groupId = {}", groupId);
        }

        // 添加人员 szUID = 5
//        FaceRecognitionModule.addPerson(groupId, passengerDO);

        // 通道撤控 通道默认为 0, 方法里通道减 1
//        ArrayList<Integer> arrayList = new ArrayList<>();
//        arrayList.add(1);
//        FaceRecognitionModule.delDisposition(groupId, arrayList);

        // 通道布控 (1,1~100)才能成功, 通道默认为 0, 方法里通道减 1
//        HashMap<Integer, Integer> hashMap = new HashMap<>();
//        hashMap.put(1, 100);
//        FaceRecognitionModule.putDisposition(groupId, hashMap);

        // 事件订阅,事件回调
        NetSDKLib.LLong success = FaceRecognitionModule.realLoadPicture(0, AnalyzerDataCallBack.getInstance());
        log.info("事件订阅状态: {}", success);

        int count = FaceRecognitionModule.startFindPerson(groupId, false, "",
                false, "", "", 1, 1, "");
        log.info("查找目标识别结果: count = {}", count);

        NetSDKLib.CANDIDATE_INFOEX[] infos = FaceRecognitionModule.doFindPerson(0, 20);
        if (infos != null) {
            log.info("----------- 查找目标识别结果 -----------");
            for (NetSDKLib.CANDIDATE_INFOEX info : infos) {
                String szUID = new String(info.stPersonInfo.szUID);
                String szPersonName = parseString(info.stPersonInfo.szPersonName);

                NetSDKLib.NET_TIME netTime = new NetSDKLib.NET_TIME(info.stuTimeRealUTC);
                log.info("netTime = {}", netTime.toString());
                log.info("nChannelID = {}", info.nChannelID);
                log.info("bySimilarity = {}", info.bySimilarity);
                log.info("wFacePicNum = {}", info.stPersonInfo.wFacePicNum);
                log.info("szUID = {}, szPersonName = {}\n", szUID, szPersonName);
            }
        }

    }

    public static String parseString(byte[] data) {
        if (data == null) return "";
        int len = 0;
        while (len < data.length && data[len] != 0) len ++;
        return new String(data, 0, len, Charset.forName("GBK"));
    }

    private static void saveImage(Pointer pBuffer, NetSDKLib.DEV_EVENT_FACERECOGNITION_INFO recognitionInfo) {
        if (recognitionInfo.bGlobalScenePic == 1) {
            log.info("----------- 保存全景图 -----------");
            String strGlobalPicPathName = "D://" + recognitionInfo.UTC.toStringTitle() + "_FaceRecognition_Global.jpg";
            byte[] bufferGlobal =
                    pBuffer.getByteArray(
                            recognitionInfo.stuGlobalScenePicInfo.dwOffSet,
                            recognitionInfo.stuGlobalScenePicInfo.dwFileLenth);
            ByteArrayInputStream byteArrInputGlobal = new ByteArrayInputStream(bufferGlobal);

            try {
                BufferedImage globalBufferedImage = ImageIO.read(byteArrInputGlobal);
                if (globalBufferedImage != null) {
                    File globalFile = new File(strGlobalPicPathName);
                    ImageIO.write(globalBufferedImage, "jpg", globalFile);
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

}
